<template>
  <transition name="bc-toast-fade" @after-leave="handleAfterLeave">
    <div v-if="visible" :style="{'zIndex':zIndex,'top':verticalOffset+'px'}" 
      :class="['bc-toast',type ? 'bc-toast--'+type : '']"
      @mouseenter="clearTimer"
      @mouseleave="startTimer">
      <bc-icon class="bc-toast__icon" name="bc-info"></bc-icon>
      <p class="bc-toast__cont" v-html="context"></p>
      <span class="bc-toast__closeBtn" @click="close" v-if="showClose">
        <bc-icon name="bc-close"></bc-icon>
      </span>
    </div>
  </transition>
</template>

<script>
export default {
  name: "BcToast",
  data() {
    return {
      visible: false,
      zIndex: 10,
      showClose: false,
      type: 'info',
      context: '',
      timer: null,
      duration:3000,
      closed: false,
      verticalOffset: 20
    };
  },
  watch: {
    closed (newVal) {
      if (newVal) {
        this.visible = false
      }
    }
  },
  computed: {
  },
  methods: {
    handleAfterLeave () {
      this.$destroy(true);
      this.$el.parentNode.removeChild(this.$el);
    },
    close() {
      this.closed = true;
      this.onClose(this);
    },
    clearTimer() {
      clearTimeout(this.timer)
    },
    startTimer() {
      if(this.duration > 0) {
        this.timer = setTimeout(() => {
          if(!this.closed) {
            this.close()
          }
        }, this.duration)
      }
    },
    keydown (e) {
      if (e.keyCode === 27) {
        // esc关闭消息
        if (!this.closed) {
          this.close()
        }
      }
    }
  },
  mounted () {
    this.startTimer();
    document.addEventListener('keydown', this.keydown);
  },
  beforeDestroy () {
    this.clearTimer();
    document.removeEventListener('keydown', this.keydown);
  }
};
</script>

<style scoped>
.bc-toast {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  min-width: 240px;
  max-width: 400px;
  background-color: #fff;
  padding: 8px 10px 8px 15px;
  border-radius: 6px;
  border: 1px solid #000;
  color: #000;
  display: flex;
  align-items: center;
}
.bc-toast-fade-enter-active,
.bc-toast-fade-leave-active {
  transition: all 0.3s linear;
}
.bc-toast-fade-enter,
.bc-toast-fade-leave-to {
   opacity: 0;
   /* 定位中设有translateX，最好让x轴的变化从对应的起时点开始 */
   transform: translate(-50%, -100%);
}
.bc-toast .bc-toast__cont {
  padding-right: 16px;
}
.bc-toast .bc-toast__icon {
  margin-right: 10px;
}
.bc-toast .bc-toast__closeBtn {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: transform 0.5s;
}
.bc-toast .bc-toast__closeBtn:hover {
  transform: rotateZ(180deg);
}
.bc-toast.bc-toast--success {
  color: #19be6b;
  border: 1px solid #19be6b;
}
.bc-toast.bc-toast--warning {
  color: #f90;
  border: 1px solid #f90;
}
.bc-toast.bc-toast--error {
  color: #ed4014;
  border: 1px solid #ed4014;
}
</style>